package cn.com.sina.finance.todolist.net;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author yuebo
 * @date 2024/10/10
 */
public class HttpUtil {

    private static OkHttpClient okHttpClient;
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    public static final int CODE_ERROR = 500;

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new LoginInterceptor())
                    .addInterceptor(new HostInterceptor())
                    .build();
        }
        return okHttpClient;
    }

    /**
     * 使用Retrofit进行http请求，目前仅登录接口使用
     *
     * @return
     */
    public static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl("http://10.222.38.41:8080/")
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
                .build();
    }

    /**
     * 自己封装的http请求
     *
     * @param url
     * @param callback
     */
    public static void get(String url, HttpCallback callback) {
        OkHttpClient okHttpClient = HttpUtil.getOkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.d("todo", "string=" + string);
                        invokeCallbackSuccess(callback, string);
                    } else {
                        invokeCallbackFail(callback, CODE_ERROR, "response.isSuccessful()=false ", null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    invokeCallbackFail(callback, CODE_ERROR, "网络请求发生异常", e);
                }
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                invokeCallbackFail(callback, CODE_ERROR, "网络请求发生异常", e);
            }
        });
    }

    public static void invokeCallbackSuccess(HttpCallback callback, String data) {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onSuccess(data);
                }
            }
        });
    }

    public static void invokeCallbackFail(HttpCallback callback, int code, String msg, Throwable e) {
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onFail(code, msg, e);
                }
            }
        });
    }
}
